package cn.kbyue.demo.gatewaydemo.config;

import com.google.common.collect.Lists;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

/**
 * @author XL
 * @version 0.1
 * @date 2022/6/10 23:08
 */
// 注: 未配置: spring.cloud.gateway.globalcors.cors-configurations 时, 可使用此配置跨域
// @Configuration
public class CorsConfig {

    @Bean
    public WebFilter corsFilter() {
        return (ServerWebExchange ctx, WebFilterChain chain) -> {
            ServerHttpRequest request = ctx.getRequest();
            final ServerHttpResponse response = ctx.getResponse();
            final HttpHeaders headers = response.getHeaders();
            headers.setAccessControlAllowOrigin("*");
            headers.setAccessControlAllowCredentials(true);
            headers.setAccessControlAllowHeaders(Lists.newArrayList("*"));
            headers.setAccessControlAllowMethods(Lists.newArrayList(HttpMethod.OPTIONS, HttpMethod.GET,
                    HttpMethod.HEAD, HttpMethod.POST, HttpMethod.DELETE, HttpMethod.PUT));
            if (request.getMethod() == HttpMethod.OPTIONS) {
                response.setStatusCode(HttpStatus.OK);
                return Mono.empty();

            }
            return chain.filter(ctx);
        };
    }

}
